package com.cyq.controller;

import com.alibaba.fastjson.JSONArray;
import com.cyq.pojo.Bill;
import com.cyq.pojo.Provider;
import com.cyq.pojo.User;
import com.cyq.service.BillService;
import com.cyq.service.ProviderService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/bill")
public class BillController {

    @Autowired
    private BillService billService;

    @Autowired
    private ProviderService providerService;

    /*实现订单列表页面*/
    @RequiresRoles(value = {"admin","master"},logical = Logical.OR)
    @GetMapping("/list")
    public ModelAndView billList(@RequestParam(required = false, defaultValue = "1", value = "pageNum") Integer pageNum,
                                 @NotNull HttpServletRequest request) {
        ModelAndView mav = new ModelAndView();

        //模糊查询取参数
        String productName = request.getParameter("queryPN");
        String providerId = request.getParameter("queryPI");
        String isPay = request.getParameter("queryIsPay");
        if (productName == "") {
            productName = null;
        }
        if (providerId == null) {
            providerId = "0";
        }
        if (isPay == null) {
            isPay = "0";
        }

        Map<String, Object> map = new HashMap<>();
        map.put("productName", productName);
        map.put("providerId", Integer.parseInt(providerId));
        map.put("isPayment", Integer.parseInt(isPay));


        PageHelper.startPage(pageNum, 8);

        try {
            List<Bill> billList = billService.getBillList(map);

            for (Bill bill : billList) {
                Provider provider = new Provider();
                provider.setId(bill.getProviderId());
                String proName = providerService.queryProByProvider(provider).getProName();
                bill.setProviderName(proName);
            }

            PageInfo<Bill> pageInfo = new PageInfo<Bill>(billList);
            mav.addObject("pageInfo", pageInfo);
        } finally {
            PageHelper.clearPage();
        }
        //获取供应商列表并传入前端
        map.put("proCode", null);
        map.put("proName", null);
        List<Provider> proList = providerService.getProList(map);
        mav.addObject("proList", proList);

        //记录查询数据
        mav.addObject("queryPN", productName);
        mav.addObject("queryPI", Integer.parseInt(providerId));
        mav.addObject("queryIsPay", Integer.parseInt(isPay));

        mav.setViewName("bill/BillList");
        return mav;
    }

    /*跳转到订单添加界面*/
    @RequiresRoles(value = {"master"},logical = Logical.OR)
    @GetMapping("/billAdd")
    public String toBillAdd() {
        return "bill/BillAdd";
    }

    /*实现订单添加*/
    @PostMapping(value = "/billAdd", produces = "application/json; charset=utf-8")
    public ModelAndView billAdd(Bill bill, HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mav = new ModelAndView();
        String method = request.getParameter("method");
        //获取当前用户
        User currentUser = (User) SecurityUtils.getSubject().getPrincipal();
        //当method为add时，代表全部输入合法，成功添加
        if (method.equals("add")) {
            bill.setCreationDate(new Date());
            bill.setCreatedBy(currentUser.getId());
            int flag = 0;
            flag = billService.billAdd(bill);
            if (flag > 0) {
                mav.setViewName("redirect:/bill/list");
            } else {
                mav.setViewName("bill/BillAdd");
            }
        }
        //ajax动态获取供应商栏参数
        else if (method.equals("getproviderlist")) {
            List<Provider> providerList = providerService.getProListNoLimit(new HashMap<String, Object>());
            try {
                //将roleList转换成json对象
                response.setContentType("application/json;charset=utf-8");
                PrintWriter writer = response.getWriter();
                writer.write(JSONArray.toJSONString(providerList));
                writer.flush();
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //ajax动态验证登录账号billCode是否已经存在
        else if (method.equals("billCodeExit")) {
            String billCode = request.getParameter("billCode");
            Map<String, String> resultMap = new HashMap<String, String>();
            if (StringUtils.isEmpty(billCode) || billCode == "") {
                resultMap.put("billCode", "empty");
            } else {
                Bill bill1 = new Bill();
                bill1.setBillCode(billCode);
                bill1 = billService.queryBillById(bill1);
                if (null != bill1) {
                    resultMap.put("billCode", "exist");
                } else {
                    resultMap.put("billCode", "notExist");
                }
            }
            try {
                //将resultMap转换成json对象
                response.setContentType("application/json;charset=utf-8");
                PrintWriter outPrintWriter = response.getWriter();
                outPrintWriter.write(JSONArray.toJSONString(resultMap));
                outPrintWriter.flush();
                outPrintWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return mav;
    }

    /*订单查看详情*/
    @RequiresRoles(value = {"master"},logical = Logical.OR)
    @RequestMapping("/billView/{id}")
    public ModelAndView BillView(@PathVariable("id") int billId) {
        ModelAndView mav = new ModelAndView();
        Bill bill = new Bill();
        //根据id查询出当前选中的供应商
        bill.setId(billId);
        bill = billService.queryBillById(bill);
        Provider provider = new Provider();
        provider.setId(bill.getProviderId());
        bill.setProviderName((providerService.queryProByProvider(provider)).getProName());
        //将数据传入前端
        mav.addObject("bill", bill);
        mav.setViewName("bill/BillView");
        return mav;
    }

    /*跳转到供应商修改页面*/
    @RequiresRoles(value = {"master"},logical = Logical.OR)
    @GetMapping("/billUpdate/{id}")
    public ModelAndView toBillModify(@PathVariable("id") int billId) {
        ModelAndView mav = new ModelAndView();
        Bill bill = new Bill();
        //根据id查询出当前选中的供应商
        bill.setId(billId);
        bill = billService.queryBillById(bill);
        //将数据传入前端
        mav.addObject("bill", bill);
        mav.setViewName("bill/BillUpdate");
        return mav;
    }

    /*订单修改*/
    @RequiresRoles(value = {"master"},logical = Logical.OR)
    @RequestMapping("/billUpdate")
    public ModelAndView BillModify(Bill bill, HttpServletRequest req) {

        ModelAndView mav = new ModelAndView();
        User currentUser = (User) SecurityUtils.getSubject().getPrincipal();
        bill.setBillCode(req.getParameter("billCode"));
        //将修改者和修改时间注入对象属性中
        bill.setModifyBy(currentUser.getId());
        bill.setModifyDate(new Date());
        int flag = billService.modifyBillById(bill);
        if (flag > 0) {
            mav.setViewName("redirect:/bill/list");
            mav.addObject("msg","修改成功");
        } else {
            mav.setViewName("redirect:/bill/billUpdate/" + bill.getId());
            mav.addObject("msg","修改失败");
        }
        return mav;
    }

    /*删除员工*/
    @RequiresRoles(value = {"master"})
    @GetMapping("/billDelete")
    public void billDelete(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("billCode");
        System.out.println(id);
        Map<String, String> resultMap = new HashMap<String, String>();
        int flag = billService.deleteBillById(Integer.parseInt(id));
        if (flag > 0) {
            resultMap.put("code", "success");
        } else {
            resultMap.put("code", "error");
        }
        try {
            response.setContentType("application/json;charset=utf-8");
            PrintWriter outPrintWriter = response.getWriter();
            outPrintWriter.write(JSONArray.toJSONString(resultMap));
            outPrintWriter.flush();
            outPrintWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
